package com.example.houseweb.controller;

import com.example.housebiz.service.AgencyService;
import com.example.housebiz.service.UserService;
import com.example.housecommon.constants.CommonConstant;
import com.example.housecommon.model.User;
import com.example.housecommon.result.ResultMsg;
import com.example.housecommon.utils.HashUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2018-05-26
 **/
@Controller
public class UserController {



    @Autowired
    private UserService userService;


    @Autowired
    private AgencyService agencyService;

    /**
     * 注册提交：1.注册验证 2.发送邮件 3.验证失败重定向到注册页面 注册页获取：根据account对象为依据判断是否注册页获取请求
     *
     * @param account
     * @param modelMap
     * @return
     */
    @RequestMapping("/accounts/register")
    public String accountsRegister(User account, ModelMap modelMap) {

        if (account == null || account.getName()==null) {
            modelMap.put("agencyList", agencyService.getAllAgency() );
            return "/user/accounts/register";
        }

        ResultMsg resultMsg = UserHelper.validate(account);
        if(resultMsg.isSuccess() && userService.addAccount(account)) {
            modelMap.put("email",account.getEmail());
            return "/user/accounts/registerSubmit";
        } else {
            return "redirect:/accounts/register?"+resultMsg.asUrlParams();
        }
    }

    @RequestMapping("/accounts/verify")
    public String verify(@RequestParam("key")String key) {
        boolean result = userService.enable(key);
        if(result){
            return "redirect:/index?"+ResultMsg.successMsg("激活成功").asUrlParams();
        } else{
            return "redirect:/accounts/register?"+ResultMsg.errorMsg("激活失败").asUrlParams();
        }
    }

//-------------------------------------登录流程-----------------------------------------


    /**
     * 登录接口
     * @return
     */
    @RequestMapping("/accounts/signin")
    public String signin(HttpServletRequest request){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //target 目标页，在拦截器中
        String target = request.getParameter("target");
        //username 与 password位零说明还没登录，转到登录页
        if (username == null || password == null) {
            request.setAttribute("target",target);
            return "/user/accounts/signin";
        }
        User user = userService.auth(username,password);
        if(user == null) {
            return "redirect:/accounts/signin?" + "target=" +target+"&username=" + username + "&"
                    + ResultMsg.errorMsg("用户名或密码错误").asUrlParams();
        } else {
            HttpSession session = request.getSession(true);
            session.setAttribute(CommonConstant.USER_ATTRIBUTE,user);
            return StringUtils.isNoneBlank(target) ? "redirect:"+target : "redirect:/index";
        }
 }


    /**
     * 登出操作
     * @param request
     * @return
     */
    @RequestMapping("/accounts/logout")
    public String logout(HttpServletRequest request) {
        HttpSession session = request.getSession(true);
        session.invalidate();
        return "redirect:/homepage/index";
    }



    //-----------------个人信息页--------------------


    /**
     * 1.能够提供页面信息
     * 2.更新用户信息
     *
     * @return
     */
    @RequestMapping("/accounts/profile")
    public String profile(HttpServletRequest request, User updateUser,ModelMap model) {
        if(updateUser.getEmail() == null ){    //email不可修改
            return "/user/accounts/profile";
        }
        userService.updateUser(updateUser,updateUser.getName());
        User query = new User();
        query.setEmail(updateUser.getEmail());
        List<User> users = userService.getUserByQuery(query);
        request.getSession(true).setAttribute(CommonConstant.USER_ATTRIBUTE,users.get(0));
        return "redirect:/accounts/profile?"+ResultMsg.successMsg("更新成功").asUrlParams();
    }


    @RequestMapping("/accounts/changePassword")
    public String changePassword(@RequestParam("name") String name,@RequestParam("password")String password, @RequestParam("newPassword")String newPassword,
                                 @RequestParam("confirmPassword") String confirmPassword, ModelMap model) {
        User user = userService.auth(name,password);
        if(user == null||!confirmPassword.equals(newPassword)) {
            return "redirect:/accounts/profile?"+ResultMsg.errorMsg("密码错误").asUrlParams();
        }
        User updateUser = new User();
        updateUser.setPasswd(HashUtils.encryPassword(newPassword));
        userService.updateUser(updateUser,name);
        return "redirect:/accounts/profile?"+ResultMsg.successMsg("更新成功").asUrlParams();
    }


}





